/**
 * 2021 4 15
 * 重写 homePage 
 * allen
 */

const app = getApp()

Component({
	properties: {
		navbarData: {
			type: Object,
			value: {}
		},
		userList: null,
		nowUserId: null,
		nowQueueId: null
	},
	data: {
		statusBarHeight: '',
		showModal: false,
		navbarData: {
			showCapsule: 1	// 默认显示左上角
		},
		disabled: true
	},
	lifetimes: {
		attached: function () {
			this.setData({ statusBarHeight: app.globalData.statusBarHeight })
		},
	},
	pageLifetimes: {
		show: function () {
			this.getUser()
		}
	},
	methods: {
		/**
		 * 开始获取用户列表信息
		 * 1.等待 cookie 就绪
		 * 2.等待获取当前的用户 userId 和 queueId 后
		 * 3.开始获取
		 */
		getUser: function () {
			let cookie = this.getCookie()
            let getCurrentUserInfo = this.getCurrent()
			Promise.all([cookie, getCurrentUserInfo])
				   .then(() => this.getUserList())
				   .catch(err => {
						wx.showToast({
							title: '获取用户列表失败！请尝试重新打开',
							icon: 'none'
						})
				   })
		},
		/**
		 * 等待 cookie 的存入
		 * @return { resolve } <promise>
		 */
		getCookie: function () {
			return new Promise(resolve => {
				let timer = setInterval(() => {
					const alreadyCookie = wx.getStorageSync('already_cookie')
					if (!alreadyCookie) return
					clearInterval(timer)
					resolve()
				}, 100)
			})
		},
		/**
		 * 等待获取当前的用户信息
		 * @return { resolve } <promise>
		 */
		getCurrent: function () {
			return new Promise(resolve => {
				let timer = setInterval(() => {
                    const { userId, queueId } = app.globalData
                    console.log('app.globalData',app.globalData)
                    clearInterval(timer)
					if (!userId || !queueId) return
					resolve()
				}, 100)
			})
		},
		/**
		 * 显示弹框
		 */
		showModalFn: function () {
            this.setData({ showModal: true })
            this.getUserList()
		},
		/**
		 * 隐藏弹框
		 */
		hideModalFn: function () {
			this.setData({ showModal: false })
		},
		/**
		 * 选中当前患者
		 * @param { object } info
		 */
		changeToUser: function (info) {
			let param = {
				userId: info.id || info.currentTarget.dataset.userid,
				queueId: info.queueId || info.currentTarget.dataset.queueid
			}
			// 切换用户
			this.checkUserInfo(param, info)
        },
        changeToUserBtn:function(info){
            let param = {
				userId: info.id || info.currentTarget.dataset.userid,
				queueId: info.queueId || info.currentTarget.dataset.queueid
            }
            this.hideModalFn();
			// 切换用户
			this.checkUserInfo(param, info)
        },
		/**
		 * 切换用户时的请求
		 * @param { object } param
		 */
		checkUserInfo: function (param, info) {
			const that = this
			return new Promise(resolve=> {
				try {
					const { username, queuename } = info.currentTarget.dataset
					wx.showLoading({ title: `正切换至${ username }(${ queuename })` })
				} catch(err) {}

				wx.request({
				  	url: app.getUrl('/xcx/pt/checkUserInfo'),
					header: wx.getStorageSync('cookie'),
					data: param,
					success: function (res) {
            console.log('res 999',res)
						if (res.data.code == 200) {
							// that.hideModalFn()
							app.globalData.userId = param.userId
							app.globalData.queueId = param.queueId
							that.setData({ 
								nowUserId: param.userId, 
								nowQueueId: param.queueId,
								userList: that.userSort(app.globalData.userList)
							})
						} else if (res.data.code == 0) {
              wx.showToast({ title: '该用户未通过审核或已被删除,切换中', icon:'none', duration:2000 })
							if (resolve.data['data'] != null) {
								app.globalData.userList = res.data.data
								app.globalData.userId = res.data.data[0].id
								app.globalData.queueId = res.data.data[0].queueId
							} else {
								app.globalData.userList = null
								app.globalData.userId = null
								app.globalData.queueId = null
							}
							that.setData({
								userList: that.userSort(app.globalData.userList)
							})
							if (app.globalData.userId && app.globalData.queueId) {
								that.setData({
									disabled: true,
									nowUserId: app.globalData.userId,
									nowQueueId: app.globalData.queueId
								})
							}
							if (app.globalData.userList == null) {
								that.setData({ disabled:true })
							}
						}
					},
					complete: function () {
						wx.hideLoading()
						// that.hideModalFn();
						const pages = getCurrentPages()
						pages.forEach(item => {
							item.onLoad && item.onLoad()
							item.onShow && item.onShow()
						})
						resolve()
					}
				})
			})
		},
		/**
		 * 添加用户
		 */
		toAddNewUser: function () {
			this.hideModalFn()
			wx.navigateTo({ url: '../guide/queue/queue?code=true' })
		},
		/**
		 * 点击退出时去设置微信用户状态
		 */
		toExitPro: function() {
			wx.request({
			  url: app.getUrl('/xcx/exit'),
				method: 'GET',
				header: wx.getStorageSync('cookie'),
				success: function (res) {
					wx.navigateBack()
				}
			})
		},
		/**
		 * 储蓄用户列表
		 */
		setUserList: function () {
			this.setData({ userList: this.userSort(app.globalData.userList) })
		},
		/**
		 * 获取用户列表
		 */
		getUserList: function () {
			let that = this
			wx.request({
				url: app.getUrl('xcx/pt/changeUsersInfo'),
				method: "GET",
				header: wx.getStorageSync('cookie'),
				success: function (res) {
					if (res.data.code == 401) {
						setTimeout(function () { that.getUserList(); }, 1000)
					}
					if (res.data.code != 0) {
						app.globalData.userList = null
						that.setData({ userList: null })
						return
					}
					app.globalData.userList = res.data.data
					const { queueId, userId } = app.globalData
					that.setData({
						nowQueueId: queueId,
						nowUserId: userId
					})
					that.judgeCurrentPatient()
					// that.setUserList()
				}
			})
			if (app.globalData.userMobile) {
				that.setData({
					disabled: false,
					nowUserId: app.globalData.userId,
					nowQueueId: app.globalData.queueId
				})
			}
		},
		judgeCurrentPatient: function () {
			if (typeof app.globalData.currentPatient == 'object') {
				const { queueId, userList, userId } = app.globalData
				userList.forEach(item => {
                    console.log('item',item)
                    console.log('userId',userId)
                    console.log('queueId',queueId)
					if (item.id === userId && item.queueId === queueId) {
						this.changeToUser(item)
					}
				})
				return
			}
			setTimeout(() => this.judgeCurrentPatient(), 1000)
		},
		/**
		 * 对用户列表进行排序, 将当前用户放至第一位
		 * @param { object[] } list 
		 * @return { object[] } list
		 */
		userSort: function (list) {
			if (!list) throw 'homePage 54 line: list is not default'
			let _index = null, _item = null
			let	{ queueId, userId } = app.globalData
			list.forEach((item, index) => {
				if (userId == item.id && queueId == item.queueId) {
					_index = index
					_item = item
				}
			})
			if (_index && _item) {
				list.splice(_index, 1)
				list.unshift(_item)
			}
			
			return list
		},
	}
})